package com.example.apigetwayserver.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
//@Order(1): 过滤器的执行顺序的先后顺序，数值越小执行越优先
@Order(-1)
@Component
public class AuthorizeFilter implements GobalFilter
{
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        1.获取请求参数
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
//        2.获取authorization参数
//        getFirst方法：获取集合中符合参数的第一个数据
        String authorization = queryParams.getFirst("authorization");
//        3.校验
        if ("amdin".equals(authorization)) {
//            放行
            return chain.filter(exchange);
        }
//        4.拦截
//        4.1设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
//        4.2 拦截请求
        return exchange.getResponse().setComplete();
    }

}
